﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightParser
{
    public partial class Messenger : ChildWindow
    {
        public Messenger()
        {
            InitializeComponent();
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
            this.Close();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void ChildWindow_Closed(object sender, EventArgs e)
        {

        }

        System.Threading.Timer Timer;
        private void ChildWindow_Loaded(object sender, RoutedEventArgs e)
        {
            mentorserviceclient.GetJobCompleted += new EventHandler<SilverWebService.GetJobCompletedEventArgs>(client_GetJobCompleted);
            mentorserviceclient.PostJobResultCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(mentorserviceclient_PostJobResultCompleted);
            this.timerDelegate = new TimerDelegate(this.CrossThreadOnTimer);
            this.exceptiondelegate = new ExceptionDelegate(this.CrossThreadException);
            this.jobhandlerdelegate = new JobHandlerDelegate(this.JobHandler);
            this.Timer = new System.Threading.Timer(new System.Threading.TimerCallback(this.OnTimer)
                , null, 1000, 500);
            InitializeDialogueScripts();
            this.WebDialogue = References.WebDialogue;
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                string identity = this.WebDialogue.GetIdentity();
                this.Dispatcher.BeginInvoke(delegate
                {
                });
            });
        }

        void mentorserviceclient_PostJobResultCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            this.Timer.Change(1000, 500);
        }

        string Contact = "iengine@citiz.net";
        SilverWebService.MentorServiceSoapClient mentorserviceclient = new SilverWebService.MentorServiceSoapClient();
        bool intimer = false;
        System.Threading.ManualResetEvent WaitHandle = new System.Threading.ManualResetEvent(false);
        void OnTimer(object o)
        {
            this.Timer.Change(int.MaxValue, int.MaxValue);
//            WaitHandle.WaitOne();
  //          intimer = true;
            mentorserviceclient.GetJobAsync(Contact, SilverWebService.JobQueueType.NewJob); 
            this.Dispatcher.BeginInvoke(this.timerDelegate);
    //        intimer = false;
        }

        JobActionDialog dlg;
        void client_GetJobCompleted(object sender, SilverWebService.GetJobCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null)
                {
                    //WaitHandle.Reset();
                    this.Dispatcher.BeginInvoke(this.jobhandlerdelegate, e.Result);
                }
                else
                    this.Timer.Change(1000, 500);
            }
            catch (Exception exp)
            {
                OnCrossThreadException(exp);
            }
        }

        void OnCrossThreadException(Exception exp)
        { 
            this.Dispatcher.BeginInvoke(this.exceptiondelegate, exp);
        }

        delegate void ExceptionDelegate(Exception exp);
        ExceptionDelegate exceptiondelegate;
        void CrossThreadException(Exception exp)
        {
            System.Windows.Browser.HtmlPage.Window.Alert(exp.ToString());
        }
        delegate void JobHandlerDelegate(SilverWebService.Job job);
        JobHandlerDelegate jobhandlerdelegate;

        LearnLangNodesDialog learnlangnodesdlg;
        void JobHandler(SilverWebService.Job job)
        {
            switch (job.Type)
            {
                case SilverWebService.JobType.LearnLangNodes:
                    SilverWebService.LearnLangNodesJob learnjob=(SilverWebService.LearnLangNodesJob)job;
                    learnlangnodesdlg = new LearnLangNodesDialog(learnjob);
                    learnlangnodesdlg.Closed += new EventHandler(learnlangnodesdlg_Closed);
                    learnlangnodesdlg.Show();
                    break;
                default:
                    dlg = new JobActionDialog(job);
                    dlg.Closed += new EventHandler(dlg_Closed);
                    dlg.Show();
                    return;
            }
        }

        void learnlangnodesdlg_Closed(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }
        void dlg_Closed(object sender, EventArgs e)
        {
            mentorserviceclient.PostJobResultAsync(dlg.Job);
        }
        delegate void TimerDelegate();
        TimerDelegate timerDelegate;
        void CrossThreadOnTimer()
        { 
        }

        private void buttonTestLearnLangNodes_Click(object sender, RoutedEventArgs e)
        {
            SilverWebService.LearnLangNodesJob job = new SilverWebService.LearnLangNodesJob();
            job.LanguageNodes = new System.Collections.ObjectModel.ObservableCollection<SilverWebService.LanguageNode>();
            SilverWebService.LanguageNode ln = new SilverWebService.LanguageNode();
            ln.Value=":";
            job.LanguageNodes.Add(ln);
            ln = new SilverWebService.LanguageNode();
            ln.Value = ")";
            job.LanguageNodes.Add(ln);
            LearnLangNodesDialog dlg = new LearnLangNodesDialog(job);
            dlg.Show();
            this.label1.Content = this.label1.GetType().FullName;
        }
        public class DialogueItem
        {
            public string Remote { get; set; }
            public string Text { get; set; }
            public string Local { get; set; }
        }
        List<DialogueItem> scripts = new List<DialogueItem>();
        void InitializeDialogueScripts()
        {
            DialogueItem item=new DialogueItem();
            item.Text="Script1";
            scripts.Add(item);
            this.dataGridDialogueScripts.ItemsSource = scripts;
        }
        private void buttonSend_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (this.richTextBoxInput.Blocks.Count == 0)
                {
                    ShowLast();
                    return;
                }
                string text = GetRichTextBoxInputText();
                if (text.Length == 0)
                {
                    return;
                }
                this.richTextBoxInput.Blocks.Clear();
                this.ProcessInput(text);
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }
        }

        string GetRichTextBoxInputText()
        {
            string text = "";
            foreach(Block block in this.richTextBoxInput.Blocks)
            {
                Paragraph pa = (Paragraph)block;
                foreach (Run run in pa.Inlines)
                {
                    text += run.Text;
                }
            }
            return text;
        }
        void ProcessInput(string inputStr)
        {
            //string inputStr = "";// (string)this.richTextBoxInput.getv();
            inputStr = inputStr.Replace("\n", "");
            this.LogDialogue(inputStr, true);
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                string response = this.WebDialogue.Dialogue(inputStr);
                this.Dispatcher.BeginInvoke(delegate
                {
                    this.LogDialogue(response, false);
                });
            });
        }

        WebDialogue WebDialogue;
        void LogDialogue(string input, bool islocal)
        {
            DialogueItem item = new DialogueItem();
            item.Text = input;
            if (islocal)
                item.Local = this.Contact;
            else
                item.Remote = "Remote";
            this.scripts.Add(item);
            this.dataGridDialogueScripts.ItemsSource = null;
            this.dataGridDialogueScripts.ItemsSource = this.scripts;
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                this.Dispatcher.BeginInvoke(delegate
                {
                    ShowLast();
                });
            });
        }

        void ShowLast()
        {
            System.Threading.Thread.Sleep(50);
            DataGridColumn column = this.dataGridDialogueScripts.Columns[0];
            this.dataGridDialogueScripts.ScrollIntoView(this.scripts[this.scripts.Count-1], column);
        }

        private void dataGridDialogueScripts_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            this.dataGridDialogueScripts.Columns[0].Width = new DataGridLength(100);
            this.dataGridDialogueScripts.Columns[1].Width = new DataGridLength(this.dataGridDialogueScripts.Width-200);
            this.dataGridDialogueScripts.Columns[0].Width = new DataGridLength(100);
        }

        private void dataGridDialogueScripts_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {

        }
    }
}

